package com.srwl.mytx.widget;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.srwl.mytx.R;
import com.srwl.mytx.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dahai2070 on 2017/2/19 0019.
 */

public class SecurityKeyBoardDialog extends DialogFragment implements View.OnClickListener {

    public static final int TYPE_SET_PAY_PASSWORD = 0;//设置支付密码
    public static final int TYPE_INPUT_OLD_PAY_PASSWORD = 1;//输入旧支付密码
    public static final int TYPE_INPUT_NEW_PAY_PASSWORD = 2;//输入新支付密码
    private static final String KEY_OF_TYPE = "keyOfType";
    private static final String KEY_OF_LIMIT = "keyOfLimit";
    private static final String TAG = "SecurityKeyBoardDialog";
    private ImageView iv_key_1, iv_key_2, iv_key_3, iv_key_4, iv_key_5, iv_key_6;//最上方的圆圈,代表输入密码的第1/2/3/4/5/6位
    private TextView tv_payLimit;
    private TextView tv_title;
    private SeekBar sb_payLimit;
    private List<ImageView> imageViewList = new ArrayList<>();
    private String[] password = new String[6];
    private OnConfirmListener mListener;
    private long lastClickTime;
    private int clickInterval = 200;//删除点击 间隔时间，也是动画持续时间
    private int payLmit;
    private OnSetPassWordListener onSetPasswordListener;

    public SecurityKeyBoardDialog() {
    }

    public static SecurityKeyBoardDialog newInstance() {
        return new SecurityKeyBoardDialog();
    }

    public static SecurityKeyBoardDialog newInstance(Integer type) {

        Bundle args = new Bundle();
        args.putInt(KEY_OF_TYPE, type);
        SecurityKeyBoardDialog fragment = new SecurityKeyBoardDialog();
        fragment.setArguments(args);
        return fragment;
    }

    public static SecurityKeyBoardDialog newInstance(Integer type, Integer payLimit) {

        Bundle args = new Bundle();
        args.putInt(KEY_OF_TYPE, type);
        args.putInt(KEY_OF_LIMIT, payLimit);
        SecurityKeyBoardDialog fragment = new SecurityKeyBoardDialog();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_key_board_dialog, container, false);
        // ButterKnife.bind(this, ll_buttonView);
        tv_payLimit = view.findViewById(R.id.tv_pay_limit);
        initSeekBar(view);
        initTitle(view);
        iv_key_1 = view.findViewById(R.id.iv_key_1);
        iv_key_2 = view.findViewById(R.id.iv_key_2);
        iv_key_3 = view.findViewById(R.id.iv_key_3);
        iv_key_4 = view.findViewById(R.id.iv_key_4);
        iv_key_5 = view.findViewById(R.id.iv_key_5);
        iv_key_6 = view.findViewById(R.id.iv_key_6);
        imageViewList.add(iv_key_1);
        imageViewList.add(iv_key_2);
        imageViewList.add(iv_key_3);
        imageViewList.add(iv_key_4);
        imageViewList.add(iv_key_5);
        imageViewList.add(iv_key_6);
        view.findViewById(R.id.rl_1).setOnClickListener(this);
        view.findViewById(R.id.rl_2).setOnClickListener(this);
        view.findViewById(R.id.rl_3).setOnClickListener(this);
        view.findViewById(R.id.rl_4).setOnClickListener(this);
        view.findViewById(R.id.rl_5).setOnClickListener(this);
        view.findViewById(R.id.rl_6).setOnClickListener(this);
        view.findViewById(R.id.rl_7).setOnClickListener(this);
        view.findViewById(R.id.rl_8).setOnClickListener(this);
        view.findViewById(R.id.rl_9).setOnClickListener(this);
        view.findViewById(R.id.rl_0).setOnClickListener(this);
        view.findViewById(R.id.rl_delete).setOnClickListener(this);
        //view.findViewById(R.id.rl_commit).setOnClickListener(this);

        return view;
    }

    void initTitle(View view) {
        tv_title = view.findViewById(R.id.tv_title);
        if (getArguments() != null) {

            switch (getArguments().getInt(KEY_OF_TYPE)) {
                case TYPE_SET_PAY_PASSWORD:
                    tv_title.setText("设置支付密码");
                    break;

                case TYPE_INPUT_OLD_PAY_PASSWORD:
                    tv_title.setText("输入原支付密码");//输入旧密码没必要显示 seekBar
                    tv_payLimit.setVisibility(View.GONE);
                    sb_payLimit.setVisibility(View.GONE);
                    break;
                case TYPE_INPUT_NEW_PAY_PASSWORD:
                    tv_title.setText("输入新支付密码");
                    sb_payLimit.setProgress(getArguments().getInt(KEY_OF_LIMIT));
                    break;
                default:
                    tv_title.setText("输入支付密码");
                    tv_payLimit.setVisibility(View.GONE);
                    sb_payLimit.setVisibility(View.GONE);
            }
        } else {
            tv_title.setText("输入支付密码");
            tv_payLimit.setVisibility(View.GONE);
            sb_payLimit.setVisibility(View.GONE);

        }
    }

    void initSeekBar(View view) {
        sb_payLimit = view.findViewById(R.id.sb_pay_limit);

        sb_payLimit.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                tv_payLimit.setText("免密额度：￥" + Utils.moneyFormat(progress));
                payLmit = progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        sb_payLimit.setProgress(1);
    }


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = new Dialog(getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // must be called before set content
        //dialog.setContentView(R.layout.bottom_dialog);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        dialog.setCanceledOnTouchOutside(true);

        // 设置宽度为屏宽、在屏幕中的位置
        Window window = dialog.getWindow();
        // window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.BOTTOM;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        wlp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(wlp);
        return dialog;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.rl_1:
                addKey("1");
                break;
            case R.id.rl_2:
                addKey("2");
                break;
            case R.id.rl_3:

                addKey("3");
                break;
            case R.id.rl_4:

                addKey("4");
                break;
            case R.id.rl_5:

                addKey("5");
                break;
            case R.id.rl_6:

                addKey("6");
                break;
            case R.id.rl_7:

                addKey("7");
                break;
            case R.id.rl_8:

                addKey("8");
                break;
            case R.id.rl_9:

                addKey("9");
                break;
            case R.id.rl_0:

                addKey("0");
                break;
            case R.id.rl_delete:
                long currentTime = System.currentTimeMillis();
                if (currentTime - lastClickTime < 200) {
                    return;
                }
                lastClickTime = currentTime;
                remnovekey();
                break;
                /*case R.id.rl_commit:
                commit();
                break;*/

        }
    }

    private void commit() {
        StringBuilder pwd = new StringBuilder();
        for (String s : password) {
            if (TextUtils.isEmpty(s)) {
                return;
            }
            pwd.append(s);
        }
        Log.d(TAG, "commit: " + pwd);
        if (mListener != null) {
            mListener.onCommit(pwd.toString());
        } else if (onSetPasswordListener != null) {
            onSetPasswordListener.onCommit(pwd.toString(), payLmit);
        }
        dismiss();

    }

    /**
     * 倒序遍历password，遇到第一个有值的，清除，跳出循环...
     */
    void remnovekey() {

        for (int i = password.length - 1; i >= 0; i--) {
            if (!TextUtils.isEmpty(password[i])) {
                password[i] = "";
                break;
            }
        }

        for (int i = imageViewList.size() - 1; i >= 0; i--) {
            if (imageViewList.get(i).isShown()) {
                final View view = imageViewList.get(i);
                ViewAnimator.animate(view).zoomOut().duration(clickInterval).onStop(new AnimationListener.Stop() {
                    @Override
                    public void onStop() {
                        view.setVisibility(View.GONE);
                    }
                }).start();
                break;
            }
        }

    }

    void addKey(String key) {

        for (int i = 0; i < password.length; i++) {
            if (TextUtils.isEmpty(password[i])) {
                password[i] = key;
                break;
            }
        }

        for (ImageView iv_key : imageViewList) {
            if (!iv_key.isShown()) {
                iv_key.setVisibility(View.VISIBLE);
                ViewAnimator.animate(iv_key).zoomIn().duration(clickInterval).start();
                break;
            }
        }
        //当输入密码的最后一位数不为空则代表已经密码输入完成，直接验证密码
        if (!TextUtils.isEmpty(password[password.length - 1])) {
            commit();
        }
    }

    public interface OnConfirmListener {
        void onCommit(String passWord);
    }

    public interface OnSetPassWordListener {
        void onCommit(String payPassWord, int payLimit);
    }

    public void setOnSetPasswordListener(OnSetPassWordListener onSetPasswordListener) {
        this.onSetPasswordListener = onSetPasswordListener;
    }

    public void setOnConfirmListener(OnConfirmListener mListener) {
        this.mListener = mListener;
    }


}
